package com.brainhealth.quartz.service.impl;

import com.brainhealth.common.constant.Constants;
import com.brainhealth.common.constant.PunctuationConstants;
import com.brainhealth.common.enums.CustomerExerciseStatus;
import com.brainhealth.common.enums.PayStatus;
import com.brainhealth.common.enums.PayType;
import com.brainhealth.common.utils.DateUtils;
import com.brainhealth.common.utils.ListUtil;
import com.brainhealth.common.utils.StringUtils;
import com.brainhealth.customer.domain.*;
import com.brainhealth.customer.domain.vo.RemainResultVO;
import com.brainhealth.customer.domain.vo.UserOnlineTimeDetail;
import com.brainhealth.customer.mapper.ExerciseOrderMapper;
import com.brainhealth.customer.mapper.SysUserEventBuriedPointResultMapper;
import com.brainhealth.customer.service.*;
import com.brainhealth.quartz.service.IBuriedPointService;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wll
 */
@Service
public class IBuriedPointServiceImpl implements IBuriedPointService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    IMechanismService mechanismService;

    @Autowired
    com.brainhealth.customer.service.IBuriedPointService buriedPointService;

    @Autowired
    ISysBuriedPointService sysBuriedPointService;

    @Autowired
    ISysBuriedPointResultService buriedPointResultService;

    @Autowired
    ISysUserEventBuriedPointService sysUserEventBuriedPointService;

    @Autowired
    ISysUserEventBuriedPointResultService sysUserEventBuriedPointResultService;

    @Autowired
    ICustomerService customerService;

    @Autowired
    ICustomerExerciseService customerExerciseService;

    @Autowired
    ISysUserOrderBuriedPointResultService sysUserOrderBuriedPointResultService;

    @Autowired
    private ExerciseOrderMapper exerciseOrderMapper;

    @Autowired
    private SysUserEventBuriedPointResultMapper sysUserEventBuriedPointResultMapper;

    @Override
    public void insertBuriedPointResult() {
        long ts = DateUtils.getTimeMillis();
        try {
            String strDate = getStrPreDate();
            logger.info("{},新增埋点统计结果开始,日期{}", ts,strDate);
            List<Mechanism> mechanismList = mechanismService.selectMechanismCollect(null);
            if (CollectionUtils.isEmpty(mechanismList)) {
                return;
            }

            List<RemainResultVO> remainResultList = sysBuriedPointService.getRemainResultList(strDate);
            Set<String> remainPaySuccessUserSet=new HashSet<>();
            Set<String> remainWakeUpQingZhuUserSet=new HashSet<>();
            //Set<String> remainPaySuccessPageUserList=new HashSet<>();
            for (Mechanism mechanism : mechanismList) {
                SysBuriedPointResult buriedPointResult = new SysBuriedPointResult();
                buriedPointResult.setDate(strDate);
                String orgNo = null != mechanism.getMechanismId() ? String.valueOf(mechanism.getMechanismId()) : null;
                buriedPointResult.setOrgNo(orgNo);
                buriedPointResult.setOrgName(mechanism.getMechanismName());

                //留存
                RemainResultVO remainResult = getRemainResult(remainResultList, orgNo);
                //去除重复用户
                if (null!=remainResult) {
                    distinctRemainData(remainResult);
                    if (StringUtils.isNotBlank(remainResult.getRemainPaySuccessPageUser())) {
                        Set<String> set = Sets.newHashSet(remainResult.getRemainPaySuccessPageUser().split(PunctuationConstants.COMMA));
                        remainPaySuccessUserSet.addAll(set);
                    }
                    if (StringUtils.isNotBlank(remainResult.getRemainWakeUpQingZhuUser())) {
                        Set<String> set = Sets.newHashSet(remainResult.getRemainWakeUpQingZhuUser().split(PunctuationConstants.COMMA));
                        remainWakeUpQingZhuUserSet.addAll(set);
                    }
                    BeanUtils.copyProperties(remainResult, buriedPointResult);
                }
                //获取前一天用户的支付结果的内容
                getPayResultStatistics(strDate, orgNo, buriedPointResult);
                //获取前一天用户的训练情况
                getCustomerExerciseStatistics(strDate, orgNo, buriedPointResult);
                buriedPointResultService.insertSysBuriedPointResult(buriedPointResult);
            }
            //合计
            SysBuriedPointResult buriedPointResult = new SysBuriedPointResult();
            buriedPointResult.setDate(strDate);
            buriedPointResult.setOrgNo(""+ Constants.ORG_NO_BURIED_POINT_DAY_SUM);
            buriedPointResult.setOrgName(""+ Constants.ORG_NAME_BURIED_POINT_DAY_SUM);
            String allRemainPaySuccessUser= CollectionUtils.isNotEmpty(remainPaySuccessUserSet) ?String.join(",",remainPaySuccessUserSet):"";
            String allRemainWakeUpQingZhuUser= CollectionUtils.isNotEmpty(remainWakeUpQingZhuUserSet)? String.join(",",remainWakeUpQingZhuUserSet):"";
            buriedPointResult.setRemainPaySuccessPageUser(allRemainPaySuccessUser);
            buriedPointResult.setRemainWakeUpQingZhuUser(allRemainWakeUpQingZhuUser);

            buriedPointResultService.insertSysBuriedPointResult(buriedPointResult);
            logger.info("{},新增埋点统计结果结束", ts);
        } catch (Exception e) {
            logger.error("{},新增埋点统计结果异常", ts, e);
        }
    }

    private String getStrPreDate()
    {
        Date date = DateUtils.getDateAfter(DateUtils.getNowDate(), -1);
        String strDate = DateUtils.getFormatDate(date, DateUtils.YYYY_MM_DD);
        return strDate;
    }

    @Override
    public void insertUserEventBuriedPointResult() {
        long ts = DateUtils.getTimeMillis();
        try{
            String date = getStrPreDate();
            logger.info("{},新增用户事件埋点统计结果开始,日期{}", ts, date);
            SysUserEventBuriedPointResult buriedPoint = new SysUserEventBuriedPointResult();
            buriedPoint.setDate(date);

            List<Long> customerIdList = sysUserEventBuriedPointResultService.selectCustomerIdList(buriedPoint);
            if (CollectionUtils.isEmpty(customerIdList)) {
                return;
            }
            List<SysUserEventBuriedPointResult> userEventBuriedPointResultList = new ArrayList<>();
            for (Long customerId : customerIdList) {
                SysUserEventBuriedPoint sysUserEventBuriedPoint=new SysUserEventBuriedPoint();
                sysUserEventBuriedPoint.setCustomerId(customerId);
                sysUserEventBuriedPoint.setDate(date);
                List<SysUserEventBuriedPoint> userEventBuriedPointList = sysUserEventBuriedPointService.selectSysUserEventBuriedPointList(sysUserEventBuriedPoint);
                List<SysUserEventBuriedPointResult> list = constructUserEventBuriedList(userEventBuriedPointList);
                userEventBuriedPointResultList.addAll(list);
            }

            //for (SysUserEventBuriedPointResult userEventBuriedPointResult : userEventBuriedPointResultList) {
            //    sysUserEventBuriedPointResultService.insertSysUserEventBuriedPointResult(userEventBuriedPointResult);
            //}
            //批量新增
            logger.info("{}，新增用户订单埋点统计结果开始================",   ts);
            int count = sysUserEventBuriedPointResultService.batchInsertSysUserEventBuriedPointResult(userEventBuriedPointResultList);
            logger.info("{}，新增用户订单埋点统计结果结束，新增数据条数{}==================",  ts, count);


            logger.info("{},新增用户事件埋点统计结果结束", ts);

            //新增用户订单埋点统计结果
            insertUserOrderBuriedList(ts);
        } catch (Exception e) {
            logger.error("{},新增用户事件埋点统计结果异常", ts, e);
        }
    }

    private void insertUserOrderBuriedList(Long ts) {
        try {
            logger.info("{},新增用户订单埋点统计结果开始", ts);

            logger.info("{},删除用户订单埋点统计结果开始", ts);
            int deleteResult = sysUserOrderBuriedPointResultService.deleteSysUserOrderBuriedPointResultById(null);
            logger.info("{},删除用户订单埋点统计结果结束，结果{}", ts,deleteResult);

            List<ExerciseOrderResult> exerciseOrderList = exerciseOrderMapper.getExerciseOrderList();
            Set<Long> customerIdSet = exerciseOrderList.stream().map(item -> item.getCustomerId()).collect(Collectors.toSet());
            List<Long> customerIdList = new ArrayList<>(customerIdSet);
            List<List<Long>> lists = ListUtil.averageAssign(customerIdList, 100);
            for (List<Long> idList : lists) {
                List<SysUserOrderBuriedPointResult> userOrderBuriedPointResultList = new ArrayList<>();
                UserEventBuriedPointQueryParam userEventBuriedPointQueryParam = new UserEventBuriedPointQueryParam();
                userEventBuriedPointQueryParam.setCustomerIdList(idList);
                List<UserOnlineTimeDetail> userOnlineTimeDetailList = sysUserEventBuriedPointResultMapper.getUserOnlineTimeStatus(userEventBuriedPointQueryParam);
                for (Long customerId : idList) {
                    Optional<ExerciseOrderResult> optionalOrderResult = exerciseOrderList.stream().filter(item -> item.getCustomerId().equals(customerId)).findFirst();
                    ExerciseOrderResult orderResult = optionalOrderResult.orElse(null);
                    String exerciseOrderNo = orderResult.getExerciseOrderNo();
                    if (StringUtils.isNotBlank(exerciseOrderNo)) {
                        SysUserOrderBuriedPointResult userOrderBuriedPointResult = getSysUserOrderBuriedPointResult(customerId, exerciseOrderNo, userOnlineTimeDetailList);
                        if (null != userOrderBuriedPointResult) {
                            userOrderBuriedPointResultList.add(userOrderBuriedPointResult);
                        }
                    }
                    String completedOrderNo = orderResult.getCompletedOrderNo();
                    if (StringUtils.isNotBlank(completedOrderNo)) {
                        SysUserOrderBuriedPointResult userOrderBuriedPointResult = getSysUserOrderBuriedPointResult(customerId, completedOrderNo, userOnlineTimeDetailList);
                        if (null != userOrderBuriedPointResult) {
                            userOrderBuriedPointResultList.add(userOrderBuriedPointResult);
                        }
                    }
                }
                //批量新增
                logger.info("{},{}批次,新增用户订单埋点统计结果开始================", idList, ts);
                int count = sysUserOrderBuriedPointResultService.batchInsertSysUserOrderBuriedPointResult(userOrderBuriedPointResultList);
                logger.info("{},{}批次,新增用户订单埋点统计结果结束，新增数据条数{}==================", idList, ts, count);
            }
            logger.info("{},新增用户订单埋点统计结果结束", ts);
        } catch (Exception e) {
            logger.error("{},新增用户订单埋点统计结果异常", ts, e);
        }
    }

    private SysUserOrderBuriedPointResult getSysUserOrderBuriedPointResult(Long customerId,String orderNos,List<UserOnlineTimeDetail> userOnlineTimeDetailList)
    {
        SysUserOrderBuriedPointResult userOrderBuriedPointResult= new SysUserOrderBuriedPointResult();
        HashSet<String> orderSet = Sets.newHashSet(orderNos.split(PunctuationConstants.COMMA));
        List<UserOnlineTimeDetail> onlineTimeList = userOnlineTimeDetailList.stream().filter(item -> orderSet.contains(item.getOrderNo()) && item.getCustomerId().equals(customerId)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(onlineTimeList)){
            return null;
        }
        UserOnlineTimeDetail onlineTime = onlineTimeList.get(0);
        BeanUtils.copyProperties(onlineTime,userOrderBuriedPointResult);
        userOrderBuriedPointResult.setAge(Long.valueOf(onlineTime.getAge()));
        userOrderBuriedPointResult.setSex(Long.valueOf(onlineTime.getSex()));
        userOrderBuriedPointResult.setStatus(PayStatus.Exercise.getCode());
        //String sex = userOnlineTimeDetail.getSex();
        //userOnlineTimeDetail.setSex(SexEnum.getSexNameByCode(sex));
        Double totalOnlineTime = onlineTimeList.stream().mapToDouble(item -> item.getOnlineTime()).sum();
        Integer totalOnlineDays = onlineTimeList.stream().mapToInt(item -> item.getOnlineDays()).sum();

        userOrderBuriedPointResult.setOnlineTime(new Double(totalOnlineTime).longValue());
        userOrderBuriedPointResult.setOnlineDays(new Integer(totalOnlineDays).longValue());
        userOrderBuriedPointResult.setCreateTime(DateUtils.getNowDate());

        return userOrderBuriedPointResult;
    }

    private List<SysUserEventBuriedPointResult> constructUserEventBuriedList( List<SysUserEventBuriedPoint> list)
    {
        //一个用户一个用户生成
        //List<SysUserEventBuriedPoint> list =new ArrayList<>();
        if (CollectionUtils.isEmpty(list)){
            return null;
        }

        List<SysUserEventBuriedPointResult> userEventBuriedPointResultList=new ArrayList<>();
        //某个订单，埋点时间倒序
        ArrayList<SysUserEventBuriedPoint> sysUserEventBuriedPointList = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(p -> p.getOrderNo()))), ArrayList::new));
        List<String> orderNoList  = sysUserEventBuriedPointList.stream().map(o -> o.getOrderNo()).collect(Collectors.toList());
        final int FIVE_MINUTES_SECONDS = 5 * 60;
        int onlineTime = 0;

        for (int i = 0; i < orderNoList.size(); i++) {
            String orderNo = orderNoList.get(i);
            List<SysUserEventBuriedPoint> userEventBuriedPointList = list.stream().filter(item -> item.getOrderNo().equals(orderNo)).collect(Collectors.toList());
            userEventBuriedPointList.sort(Comparator.comparing(SysUserEventBuriedPoint::getCreateTime).reversed());
            if (userEventBuriedPointList.size() == 1) {
                SysUserEventBuriedPointResult userEventBuriedPointResult = constructSysUserEventBuriedPointResult(userEventBuriedPointList.get(0), onlineTime);
                userEventBuriedPointResultList.add(userEventBuriedPointResult);
                //sysUserEventBuriedPointResultService.insertSysUserEventBuriedPointResult(userEventBuriedPointResult);
                continue;
            }

            for (int j = 0; j < userEventBuriedPointList.size()-1; j++) {
                SysUserEventBuriedPoint firstBuriedPoint = userEventBuriedPointList.get(j);
                SysUserEventBuriedPoint secondBuriedPoint = userEventBuriedPointList.get(j+1);
                int timeSpan = DateUtils.differentSecondByMillisecond(firstBuriedPoint.getCreateTime(), secondBuriedPoint.getCreateTime());
                if (timeSpan <= FIVE_MINUTES_SECONDS) {
                    onlineTime+=timeSpan;
                }
            }
            SysUserEventBuriedPointResult userEventBuriedPointResult = constructSysUserEventBuriedPointResult(userEventBuriedPointList.get(0), onlineTime);
            userEventBuriedPointResultList.add(userEventBuriedPointResult);
            //sysUserEventBuriedPointResultService.insertSysUserEventBuriedPointResult(userEventBuriedPointResult);
        }
        return userEventBuriedPointResultList;
    }

    private SysUserEventBuriedPointResult constructSysUserEventBuriedPointResult(SysUserEventBuriedPoint userEventBuriedPoint,long onlineTime)
    {
        if (null == userEventBuriedPoint) {
            return null;
        }
        SysUserEventBuriedPointResult userEventBuriedPointResult = new SysUserEventBuriedPointResult();
        BeanUtils.copyProperties(userEventBuriedPoint, userEventBuriedPointResult);
        Customer customer = customerService.selectCustomerByCustomerId(userEventBuriedPoint.getCustomerId());
        userEventBuriedPointResult.setPhone(customer.getPhone());
        String orgNo = null != customer && null != customer.getMechanismId() ? String.valueOf(customer.getMechanismId()) : null;
        userEventBuriedPointResult.setOrgNo(orgNo);
        //机构编号
        Mechanism mechanism = null;
        if (StringUtils.isNotBlank(orgNo)) {
            mechanism = mechanismService.selectMechanismByMechanismId(Long.valueOf(orgNo));
        }
        String orgName = null != mechanism ? mechanism.getMechanismName() : null;
        userEventBuriedPointResult.setOrgName(orgName);
        userEventBuriedPointResult.setAge(customer.getAge());
        userEventBuriedPointResult.setSex(customer.getSex());
        userEventBuriedPointResult.setOnlineTime(onlineTime);
        return userEventBuriedPointResult;
    }

    private void distinctRemainData(RemainResultVO remainResult)
    {
        if (null==remainResult){
            return;
        }
        String remainEnterDetailPageUser = remainResult.getRemainEnterDetailPageUser();
        Set<String> detailSet = distinctCustomerId(remainEnterDetailPageUser);
        if (CollectionUtils.isNotEmpty(detailSet)){
            remainEnterDetailPageUser = String.join(PunctuationConstants.COMMA, detailSet);
            remainResult.setRemainEnterDetailPageUser(remainEnterDetailPageUser);
            remainResult.setRemainEnterDetailPageUserCount(detailSet.size());
        }
        String remainEnterRegisterPageUser = remainResult.getRemainEnterRegisterPageUser();
        Set<String> registerSet = distinctCustomerId(remainEnterRegisterPageUser);
        if (CollectionUtils.isNotEmpty(registerSet)){
            remainEnterRegisterPageUser=String.join(PunctuationConstants.COMMA, registerSet);
            remainResult.setRemainEnterRegisterPageUser(remainEnterRegisterPageUser);
            remainResult.setRemainEnterRegisterPageUserCount(registerSet.size());
        }
        String remainEnterPayPageUser = remainResult.getRemainEnterPayPageUser();
        Set<String> paySet = distinctCustomerId(remainEnterPayPageUser);
        if (CollectionUtils.isNotEmpty(paySet)){
            remainEnterPayPageUser=String.join(PunctuationConstants.COMMA,paySet);
            remainResult.setRemainEnterPayPageUser(remainEnterPayPageUser);
            remainResult.setRemainEnterPayPageUserCount(paySet.size());
        }
        String remainPaySuccessPageUser = remainResult.getRemainPaySuccessPageUser();
        Set<String> paySuccessSet = distinctCustomerId(remainPaySuccessPageUser);
        if (CollectionUtils.isNotEmpty(paySuccessSet)){
            remainPaySuccessPageUser = String.join(PunctuationConstants.COMMA,paySuccessSet);
            remainResult.setRemainPaySuccessPageUser(remainPaySuccessPageUser);
            remainResult.setRemainPaySuccessPageUserCount(paySuccessSet.size());
        }
        String remainWakeUpQingZhuUser = remainResult.getRemainWakeUpQingZhuUser();
        Set<String> wakeUpQingZhuSet = distinctCustomerId(remainWakeUpQingZhuUser);
        if (CollectionUtils.isNotEmpty(wakeUpQingZhuSet)){
            remainWakeUpQingZhuUser = String.join(PunctuationConstants.COMMA,wakeUpQingZhuSet);
            remainResult.setRemainWakeUpQingZhuUser(remainWakeUpQingZhuUser);
        }
    }

    private Set<String> distinctCustomerId(String customerIds)
    {
        if (StringUtils.isNotBlank(customerIds)){
            HashSet<String> set = Sets.newHashSet(customerIds.split(PunctuationConstants.COMMA));
            return set;
        }
        return null;
    }

    private RemainResultVO getRemainResult(List<RemainResultVO> remainResultList,String orgNo){
        Optional<RemainResultVO> optionalRemainResultVO = remainResultList.stream().filter(item -> item.getOrgNo().equals(orgNo)).findFirst();
        RemainResultVO remainResultVO = optionalRemainResultVO.orElse(null);
        return remainResultVO;
    }

    /**
     * 支付结果统计
     * @param preDate 前一天的日期
     * @param orgNo 机构Id
     * @param sysBuriedPointResult 埋点数据表的对象
     * @return 埋点数据表的对象
     */
    private SysBuriedPointResult getPayResultStatistics(String preDate, String orgNo, SysBuriedPointResult sysBuriedPointResult)
    {
        BuriedPointQuery buriedPointQuery = new BuriedPointQuery();
        buriedPointQuery.setStartTime(preDate + " 00:00:00");
        buriedPointQuery.setEndTime(preDate + " 23:59:59");
        buriedPointQuery.setOrgNo(Long.valueOf(orgNo));
        List<Customer> lstCustomer = customerService.selectCustomerOrderList(buriedPointQuery);
        if (CollectionUtils.isEmpty(lstCustomer)){
            return sysBuriedPointResult;
        }
        for (Customer customer : lstCustomer)
        {
            int orderSize = CollectionUtils.isEmpty(customer.getLstOrder()) ? 0 : customer.getLstOrder().size();
            sysBuriedPointResult.setPayOrderNumberTotal( handleInteger(sysBuriedPointResult.getPayOrderNumberTotal() )+ orderSize);
            Long alipayCount = customer.getLstOrder().stream().filter(item -> item.getPayType() == PayType.Alipay).count();
            Long wechatCount = customer.getLstOrder().stream().filter(item -> item.getPayType() == PayType.Wechat).count();
            sysBuriedPointResult.setPayOrderNumberTotalAlipay(handleInteger(sysBuriedPointResult.getPayOrderNumberTotalAlipay()) + alipayCount.intValue());
            sysBuriedPointResult.setPayOrderNumberTotalWechatPay(handleInteger(sysBuriedPointResult.getPayOrderNumberTotalWechatPay()) + wechatCount.intValue());
            BigDecimal payAmountTotal = customer.getLstOrder().stream().map(ExerciseOrder::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            sysBuriedPointResult.setPayOrderAmountTotal(handleBigDecimal(sysBuriedPointResult.getPayOrderAmountTotal()).add(payAmountTotal));
            BigDecimal alipayAmount = customer.getLstOrder().stream().filter(item -> item.getPayType() == PayType.Alipay).map(ExerciseOrder::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal wechatAmount = customer.getLstOrder().stream().filter(item -> item.getPayType() == PayType.Wechat).map(ExerciseOrder::getPayAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            sysBuriedPointResult.setPayOrderAmountTotalAlipay(handleBigDecimal(sysBuriedPointResult.getPayOrderAmountTotalAlipay()).add(alipayAmount));
            sysBuriedPointResult.setPayOrderAmountTotalWechatPay(handleBigDecimal(sysBuriedPointResult.getPayOrderAmountTotalWechatPay()).add(wechatAmount));
        }
        return sysBuriedPointResult;
    }

    private Integer handleInteger(Integer integer) {
        return null == integer ? 0 : integer;
    }

    private BigDecimal handleBigDecimal(BigDecimal bigDecimal) {
        return null == bigDecimal ? new BigDecimal(0) : bigDecimal;
    }

    /**
     * 会员训练情况统计
     * @param preDate 前一天的日期
     * @param orgNo 机构Id
     * @param sysBuriedPointResult 埋点数据表的对象
     * @return 埋点数据表的对象
     */
    private SysBuriedPointResult getCustomerExerciseStatistics(String preDate, String orgNo, SysBuriedPointResult sysBuriedPointResult)
    {
        BuriedPointQuery buriedPointQuery = new BuriedPointQuery();
        buriedPointQuery.setUpdateStartTime(preDate + " 00:00:00");
        buriedPointQuery.setUpdateEndTime(preDate + " 23:59:59");
        buriedPointQuery.setOrgNo(Long.valueOf(orgNo));
        List<Customer> lstCustomer = customerService.selectCustomerOrderList(buriedPointQuery);
        if (CollectionUtils.isEmpty(lstCustomer)){
            return sysBuriedPointResult;
        }
        List<ExerciseOrder> lstFinishOrder = new ArrayList<>();
        for (Customer customer : lstCustomer)
        {
            lstFinishOrder.addAll(customer.getLstOrder().stream().filter(item -> item.getStatus() == PayStatus.Finish).collect(Collectors.toList()));
        }
        sysBuriedPointResult.setRemainCompletedUserTotal(lstFinishOrder.size());
        for (ExerciseOrder order : lstFinishOrder)
        {
            CustomerExercise query = new CustomerExercise();
            query.setOrderId(order.getOrderId());
            List<CustomerExercise> lstExercise = customerExerciseService.selectCustomerExerciseList(query);
            Long exerciseCount = lstExercise.stream().filter(item -> item.getStatus() == CustomerExerciseStatus.Finished).count();
            if (exerciseCount >= 1 && exerciseCount <= 7)
            {
                sysBuriedPointResult.setRemainCompletedUser17(sysBuriedPointResult.getRemainCompletedUser17() + exerciseCount.intValue());
            }
            if (exerciseCount >= 8 && exerciseCount <= 14)
            {
                sysBuriedPointResult.setRemainCompletedUser814(sysBuriedPointResult.getRemainCompletedUser814() + exerciseCount.intValue());
            }
            if (exerciseCount >= 15 && exerciseCount <= 21)
            {
                sysBuriedPointResult.setRemainCompletedUser1521(sysBuriedPointResult.getRemainCompletedUser1521() + exerciseCount.intValue());
            }
            if (exerciseCount >= 22)
            {
                sysBuriedPointResult.setRemainCompletedUser2228(sysBuriedPointResult.getRemainCompletedUser2228() + exerciseCount.intValue());
            }
        }
        if (CollectionUtils.isNotEmpty(lstCustomer)) {
            Integer remainCompletedUser17 = handleInteger(sysBuriedPointResult.getRemainCompletedUser17());
            Integer remainCompletedUser814 = handleInteger(sysBuriedPointResult.getRemainCompletedUser814());
            Integer remainCompletedUser1521 = handleInteger(sysBuriedPointResult.getRemainCompletedUser1521());
            Integer remainCompletedUser2228 = handleInteger(sysBuriedPointResult.getRemainCompletedUser2228());
            int finishTotal = remainCompletedUser17 + remainCompletedUser814 + remainCompletedUser1521 + remainCompletedUser2228;
            sysBuriedPointResult.setRemainCompletedUserAverage(finishTotal / lstCustomer.size());
        }

        return sysBuriedPointResult;
    }
}
